package cn.edu.qfnu.common.validation;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * OnlineJudge of QF_NU
 * Created by LS on 2017/7/19.
 */
public class MailCheck {

    public static boolean sendEmail(String email, String code) {
        try {
            Properties properties = new Properties();

            properties.setProperty("mail.debug", "true");
            properties.put("mail.smtp.host", "smtp.qq.com");  //设置SMTP主机
            properties.put("mail.smtp.auth", "true"); //通过验证
            properties.setProperty("mail.transport.protocol", "smtp");

            MailSSLSocketFactory socketFactory = new MailSSLSocketFactory();
            socketFactory.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", socketFactory);

            Session session = Session.getInstance(properties);

            Message message = new MimeMessage(session);
            message.setSubject("test");

            String sendText = "还差最后一步就能完成注册啦\n快把这个验证码：" + code + "\n输入到网站上完成注册吧！";

            message.setText(sendText);
            message.setFrom(new InternetAddress("850340309@qq.com", "admin@edu.qfnu.cn"));

            Transport transport = session.getTransport();
            transport.connect("smtp.qq.com", "850340309@qq.com", "hsecopgwjyklbcfe");
            transport.sendMessage(message, new Address[]{new InternetAddress(email)});
            transport.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
